package com.xxs.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.xxs.common.Const;
import com.xxs.common.WebUtils;
import com.xxs.utils.Context;
import com.xxs.utils.xml.XmlDom4jUtils;

/**
 * Created with IntelliJ IDEA.
 * Author: StevenChow
 * Date: 13-3-30
 */
public class GlobalInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        String siteId = resolveSite(controller);
        String siteName = Context.getCurrentSiteName(controller.getSession(), siteId);
        String siteCode = Context.getCurrentSiteCode(controller.getSession(), siteId);
        controller.setAttr("siteId", siteId);
        controller.setAttr("siteName", siteName);
        controller.setAttr("siteCode", siteCode);
        inv.invoke();
    }
    
    private String resolveSite(Controller controller) {
    	HttpSession session = controller.getSession();
    	HttpServletRequest request = controller.getRequest();
    	HttpServletResponse response = controller.getResponse();
    	String siteId = Context.getCurrentSiteId(session);
    	// 从域名中获取
    	if(siteId==null || "".equals(siteId)){
		    System.out.println("当前的getServerName是："+ controller.getRequest().getServerName());
		        String domain = controller.getRequest().getServerName();
		        siteId = XmlDom4jUtils.getParaValueByAttrAndValue(Const.SITE_PATH,"site","domain",domain,"id");
		        Context.setCurrentSiteId(controller.getSession(), siteId);
		        Context.setCurrentSiteName(controller.getSession(), siteId);
		        Context.setCurrentSiteCode(controller.getSession(), siteId);
				WebUtils.setCookie(response, "siteId",siteId,10000000);
//				WebUtils.setCookie(response, "siteName",siteName,10000000);
//				WebUtils.setCookie(response, "siteCode",siteCode,10000000);
		}
//		Site site = null;
		// 从parameter中获取
//		String siteIdText = request.getParameter(SITE_KEY);
//		if (StringUtils.isNotBlank(siteIdText)) {
//			try {
//				siteId = Integer.parseInt(siteIdText);
//				site = siteShiroService.get(siteId);
//			} catch (Exception e) {
//				// continue
//			}
//		}
		// 从cookie中获取
    	if(siteId==null || "".equals(siteId)){
    		siteId = WebUtils.getCookie(request, "siteId");
    		Context.setCurrentSiteId(controller.getSession(), siteId);
		}
		// 从数据库中获得主站
    	if(siteId==null || "".equals(siteId)){
    		siteId = XmlDom4jUtils.getParaValueByAttrAndValue(Const.SITE_PATH,"site","default","true","id");
    		Context.setCurrentSiteId(session, siteId);
    		String siteName = XmlDom4jUtils.getParaValueByAttrAndValue(Const.SITE_PATH,"site","id",siteId,"name");
        	String siteCode = XmlDom4jUtils.getParaValueByAttrAndValue(Const.SITE_PATH,"site","id",siteId,"code");
        	Context.setCurrentSiteName(controller.getSession(),siteName);
        	Context.setCurrentSiteCode(controller.getSession(),siteCode);
        	WebUtils.setCookie(response, "siteId",siteId,10000000);
			WebUtils.setCookie(response, "siteName",siteName,10000000);
			WebUtils.setCookie(response, "siteCode",siteCode,10000000);
    	}
//		if (site == null) {
//			site = siteShiroService.findDefault();
//		}
//		// 获取第一个有权限的站点
//		Subject subject = SecurityUtils.getSubject();
//		ShiroUser shiroUser = (ShiroUser) subject.getPrincipal();
//		if (shiroUser != null) {
//			List<Site> siteList = siteShiroService.findByUserId(shiroUser.id);
//			if (!siteList.isEmpty()) {
//				boolean contains = false;
//				if (site != null) {
//					for (Site s : siteList) {
//						if (s.getId().equals(site.getId())) {
//							contains = true;
//							break;
//						}
//					}
//				}
//				if (!contains) {
//					site = siteList.iterator().next();
//				}
//			}
//		}
//		if (site != null) {
//			clearPermCache(request, site.getId());
//			addSiteCookie(site.getId().toString(), request, response);
//			return site;
//		} else {
//			// 站点必须存在
//			throw new CmsException("site.error.siteNotFound");
//		}
		return siteId;
	}

}
